package com.example.fms.service.impl;

import ch.qos.logback.classic.spi.EventArgUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.fms.dto.resp.MenusDto;
import com.example.fms.dto.resp.RoleRightDTO;
import com.example.fms.entity.Right;
import com.example.fms.entity.Role;
import com.example.fms.entity.RoleRights;
import com.example.fms.entity.UserRole;
import com.example.fms.mapper.RightMapper;
import com.example.fms.mapper.RoleMapper;
import com.example.fms.mapper.RoleRightsMapper;
import com.example.fms.mapper.UserRoleMapper;
import com.example.fms.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    RoleMapper roleMapper;
    @Resource
    RoleRightsMapper roleRightsMapper;
    @Resource
    RightMapper rightMapper;
    @Resource
    UserRoleMapper userRoleMapper;


    @Override
    public List<RoleRightDTO> getRoles() {
        List<RoleRightDTO> roleRightDTOList = new ArrayList<>();

        List<Role> roles = roleMapper.selectList(null);
        for (Role role : roles) {
            RoleRightDTO roleDTO = new RoleRightDTO();
            roleDTO.setRoleName(role.getRoleName());
            roleDTO.setRoleDesc(role.getRoleName());
            roleDTO.setId(role.getId());
            // 获取角色的所有权限
            LambdaQueryWrapper<RoleRights> qw = new LambdaQueryWrapper<>();
            qw.eq(RoleRights::getRole, role.getId());
            List<RoleRights> roleRights = roleRightsMapper.selectList(qw);
            if (roleRights != null && !roleRights.isEmpty()){
                //获取roleRights中所有的rightsId
                List<Long> rightsIdList = roleRights.stream().map(RoleRights::getRightsId).collect(Collectors.toList());
                List<MenusDto> rightDTOList = getMenusByIds(rightsIdList);
                roleDTO.setChildren(rightDTOList);
            }
            roleRightDTOList.add(roleDTO);
        }
        return roleRightDTOList;
    }

    @Override
    public Boolean rolesPost(RoleRightDTO req) {
        Role role = new Role();
        role.setRoleName(req.getRoleName());
        role.setRoleDesc(req.getRoleDesc());
        roleMapper.insert(role);
        return true;
    }

    @Override
    public RoleRightDTO getRolesById(Long id) {
        Role role = roleMapper.selectById(id);
        RoleRightDTO roleRightDTO = new RoleRightDTO();
        roleRightDTO.setRoleId(role.getId());
        roleRightDTO.setRoleName(role.getRoleName());
        roleRightDTO.setRoleDesc(role.getRoleDesc());
        return roleRightDTO;
    }

    @Override
    public UserRole getRolesByUserId(Long id) {
        LambdaQueryWrapper<UserRole> qw = new LambdaQueryWrapper<>();
        qw.eq(UserRole::getUserId, id);
        return userRoleMapper.selectOne(qw);
    }


    @Override
    public Boolean updateRoleById(RoleRightDTO req,Long id) {
        Role role = new Role();
        role.setId(id);
        role.setRoleName(req.getRoleName());
        role.setRoleDesc(req.getRoleDesc());
        roleMapper.updateById(role);
        return true;
    }

    @Override
    public Boolean deleteRoleById(Long id) {
        roleMapper.deleteById(id);
        LambdaQueryWrapper<RoleRights> qw = new LambdaQueryWrapper<>();
        qw.eq(RoleRights::getRole, id);
        roleRightsMapper.delete(qw);
        return true;
    }

    @Override
    public Boolean saveRights(Long id, RoleRightDTO req) {
        LambdaQueryWrapper<RoleRights> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleRights::getRole, id);
        roleRightsMapper.delete(queryWrapper);
        String rids = req.getRids();
        //将rids按照逗号分割
        List<Long> ridsList = Arrays.stream(rids.split(",")).map(Long::parseLong).toList();
        LambdaQueryWrapper<Right> qw = new LambdaQueryWrapper<>();
        qw.in(Right::getId, ridsList);
        List<Right> rights = rightMapper.selectList(qw);
        //过滤出rights中level为3的菜单
        List<Long> rightsIdList = rights.stream().map(Right::getId).toList();
        if(!CollectionUtils.isEmpty(rightsIdList)){
            rightsIdList.forEach( s -> {
                RoleRights roleRights = new RoleRights();
                roleRights.setRole(id);
                roleRights.setRightsId(s);
                roleRightsMapper.insert(roleRights);
            });
        }

        return true;
    }

    @Override
    public Boolean deleteRoleRightsById(Long id, Long rightId) {
        Right right = rightMapper.selectById(id);
        if (right != null) {
            List<Long> longs = permissionAcquisition(rightId);
            roleRightsMapper.deleteByRoleAndIdAndRightsIdList(id,longs);
        }
        return true;
    }

    @Override
    public Role selectById(Long roleId) {
        return roleMapper.selectById(roleId);
    }

    public List<Long> permissionAcquisition(Long id) {
        LambdaQueryWrapper<Right> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Right::getId, id);
        List<Right> rights = rightMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(rights)) {
            //获取rights中所有的id
            List<Long> rids = rights.stream().map(Right::getId).toList();
            LambdaQueryWrapper<Right> qw = new LambdaQueryWrapper<>();
            qw.in(Right::getPid, rids);
            List<Right> rightsTwo = rightMapper.selectList(qw);
            if (!CollectionUtils.isEmpty(rightsTwo)) {
                LambdaQueryWrapper<Right> qwTwo = new LambdaQueryWrapper<>();
                qwTwo.in(Right::getPid, rids);
                List<Right> rightsTree = rightMapper.selectList(qwTwo);
                List<Long> list = new ArrayList<>(rightsTree.stream().map(Right::getId).toList());
                list.add(id);
                return list;
            } else {
                return rids;
            }
        } else {
            return Collections.singletonList(id);
        }
    }

    public List<MenusDto> getMenusByIds(List<Long> ids) {
        List<Right> rights = rightMapper.selectList( new LambdaQueryWrapper<Right>().in(Right::getId, ids));
        Map<Long, List<Right>> rightMap = rights.stream().collect(Collectors.groupingBy(Right::getPid));
        // 初始化一级菜单列表
        List<MenusDto> rootMenus = new ArrayList<>();
        for (Right auth : rights) {
            if (auth.getPid() == null || auth.getPid() == 0) {
                MenusDto menusDto = new MenusDto();
                // 如果PID为0或null，则为一级菜单
                menusDto.setPid(auth.getPid());
                menusDto.setId(auth.getId());
                menusDto.setAuthName(auth.getAuthName());
                menusDto.setPath(auth.getPath());
                menusDto.setLevel(auth.getLevel());
                menusDto.setChildren(buildMenuTree(rightMap, auth.getId()));
                rootMenus.add(menusDto);
            }
        }
        return rootMenus;
    }

    private List<MenusDto> buildMenuTree(Map<Long, List<Right>> authMap, Long pid) {
        List<MenusDto> children = new ArrayList<>();
        List<Right> auths = authMap.getOrDefault(pid, new ArrayList<>());
        for (Right auth : auths) {
            MenusDto menusDto = new MenusDto();
            menusDto.setPid(auth.getPid());
            menusDto.setId(auth.getId());
            menusDto.setAuthName(auth.getAuthName());
            menusDto.setPath(auth.getPath());
            menusDto.setLevel(auth.getLevel()); // 将Auth对象属性复制到MenusDto对象
            menusDto.setChildren(buildMenuTree(authMap, auth.getId()));
            children.add(menusDto);
        }
        return children;
    }


}



